<?php
declare (strict_types=1);

namespace app\circle\logic;

use app\circle\model\Circle as CircleModel;
use app\common\exception\LogicException;
use app\common\logic\Common;
use Exception;
use think\db\exception\DbException;
use think\Paginator;

/**
 * 圈子逻辑层
 */
class Circle extends CircleModel
{

    /**
     * 发布圈子
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param [description]
     */
    public function createCircle(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($param);
        // 参数
        $param['user_id'] = request()->mid;
        $param['mhm_id']  = request()->user->mhm_id;
        $param['type']    = 1;
        $param['attach']  = isset($param['attach']) ? array_map(function ($value) {
            return intval($value);
        }, explode(',', $param['attach'])) : null;
        // 内容过滤
        $param['content'] = app(Common::class)->filterSensitive($param['content'], $param['user_id'], 'circle');

        $create = $this::create($param);

        if ($create->isEmpty()) throw new LogicException('发布失败');
    }

    /**
     * 删除圈子
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-06-17
     */
    public function deleteCircle(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('delete')->failException()->check($param);
        // 参数
        $mid = request()->mid;
        $id  = intval($param['id']);

        $data = $this->findOrFail($id);
        if ($data->user_id != $mid) throw new LogicException('无删除权限');
        if (!$data->delete()) throw new LogicException('删除失败');
    }

    /**
     * 圈子列表
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getCircleList(array $param): Paginator
    {
        // 验证数据
        $this->getValidate()->scene('list')->failException()->check($param);
        // 参数
        $type = $param['type'];
        $mid  = request()->mid;

        switch ($type) {
            // 推荐
            case 1:
                $list = $this->with(['user_base', 'orignal'])->withCount(['like' => 'is_like', 'has_follow_this_person' => 'followed', 'user_vip' => 'is_vip'])->where('recommend', 1)->order('create_time DESC')->paginate(static::getListRows());

                break;
            // 关注
            case 3:
                if (!$mid) throw new LogicException('请登录');

                $list = $this->alias('c')->with(['like', 'user_base', 'orignal'])->join('user_follow f', "f.user_id=$mid AND f.follow_user_id=c.user_id AND f.delete_time is NULL")->field('c.*')->order('create_time DESC')->paginate(static::getListRows())->each(function ($i) {
                    $i->is_like = $i->like ? 1 : 0;
                    unset($i->like);
                    $i->is_vip = $i->user_vip ? 1 : 0;
                    unset($i->user_vip);
                });
                break;
            // 广场
            default:
                $list = $this->with(['user_base', 'orignal'])->withCount(['like' => 'is_like', 'has_follow_this_person' => 'followed', 'user_vip' => 'is_vip'])->order('create_time DESC')->paginate(static::getListRows());
                break;
        }

        return $list;
    }

    /**
     * 转载圈子时渲染数据
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param [description]
     */
    public function recircleFetch(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('fetch')->failException()->check($param);
        // 参数
        $id   = $param['orignal_id'];
        $data = $this->with(['user_base'])->field('id,user_id,content,attach')->findOrEmpty($id);

        if ($data->isEmpty()) throw new LogicException('转载失败');

        return $data;
    }

    /**
     * 转载圈子
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param
     * @throws Exception
     */
    public function recircle(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('recircle')->failException()->check($param);
        // 参数
        $param['user_id'] = request()->mid;
        $param['type']    = 2;
        $param['attach']  = isset($param['attach']) ? explode(',', $param['attach']) : null;

        $this->startTrans();
        try {
            $create = $this::create($param);

            if ($create->isEmpty()) throw new LogicException('转载失败');

            $orignal               = $this->findOrEmpty($param['orignal_id']);
            $orignal->recircle_num += 1;
            if (!$orignal->save()) throw new LogicException('转载失败');

            $this->commit();
        } catch (LogicException|Exception $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }
    }

    /**
     * 圈子详情
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param
     * @return array
     */
    public function getCircle(array $param): array
    {
        // 验证数据
        $this->getValidate()->scene('detail')->failException()->check($param);
        // 参数
        $id = intval($param['circle_id']);
        // 数据
        $detail  = $this->with(['user_base', 'orignal'])->withCount(['like' => 'is_like', 'has_follow_this_person' => 'followed'])->findOrFail($id);
        $comment = app(Comment::class)->getCircleCommentById($id);

        return ['detail' => $detail, 'comment' => $comment];
    }

    /**
     * 我的圈子列表
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param int $mid
     * @return mixed
     */
    public function getMyCircleList(int $mid = 0)
    {
        // 参数
        $mid = $mid ?: request()->mid;

        return $this->with(['user_base', 'orignal'])
            ->withCount(['like' => 'is_like', 'has_follow_this_person' => 'followed'])
            ->whereUserId($mid)
            ->order('create_time DESC')
            ->paginate(static::getListRows());
    }

    /**
     * 用户圈子列表
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date 2021-05-14
     *
     * @param array $param
     * @return mixed
     */
    public function getUserCircleList(array $param)
    {
        // 验证数据
        $this->getValidate()->scene('user')->failException()->check($param);
        // 参数
        $user_id = intval($param['user_id']);

        return $this->getMyCircleList($user_id);
    }

}
